package org.iris.utils;

import java.sql.*;

/**
 * @ClassName ClickHouseTest
 * @Description ClickHouse建表、查询测试
 * @Author zhanghongguo
 * @Date 2021/12/20 10:49
 * @Version 1.0
 */
public class ClickHouseTest {

    public static Connection connection;

    public static void main(String[] args) {
       /* //1、建表
        createTable("172.16.1.189","8123");
        //2、批量插入数据
        batchInsert("172.16.1.189","8123");*/
        //3、查询
        getResult("172.16.1.189","8123");
    }


    //1、建表
    public static void createTable(String host,String port){

        //初始化连接
        initConnection(host,port);
        try {
            connection.createStatement().executeQuery("create table test.jdbc_example(day Date, name String, age UInt8) Engine=Log");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //2、批量插入
    public static void batchInsert(String host,String port){
        initConnection(host,port);
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("insert into test.jdbc_example values(?, ?, ?)");
            for (int i = 0; i < 10; i++) {
                preparedStatement.setDate(1,new Date(System.currentTimeMillis()));
                preparedStatement.setString(2,"panda_"+(i+1));
                preparedStatement.setInt(3,i+18);
                preparedStatement.addBatch();
            }
            preparedStatement.executeBatch();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //3、查询
    public static void getResult(String host,String port){
        initConnection(host,port);
        try {
            ResultSet resultSet = connection.createStatement().executeQuery("select * from test.jdbc_example");
            while (resultSet.next()){
                System.out.println(resultSet.getDate(1)+" "+resultSet.getString(2)+" "+resultSet.getInt(3));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static void initConnection(String host, String port) {
        try {
            Class.forName("ru.yandex.clickhouse.ClickHouseDriver");
            String url = String.format("jdbc:clickhouse://%s:%s", host, port);
            connection = DriverManager.getConnection(url);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}


